//
//  IMAConversationManager.m
//  TIMAdapter
//
//  Created by AlexiChen on 16/2/18.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "IMAConversationManager.h"
#import "XLIMViewModel.h"
#import "CallRecvViewController.h"
#import "CallMakeViewController.h"
#import "XLV2LoginViewController.h"
#import "XLOrderPeopleModel.h"
#import "PeerModel.h"

#import "XLHTTPSessionManager+Camgirl.h"
#import "HomeCallModel.h"
#import "CallMakeViewController.h"
#import "TopUpViewController.h"
#import "XLRecVoiceChatVC.h"
#import "XLMakeVoiceChatVC.h"
//#import "IMAConversationManager+CallMessageParase.h"
@implementation IMAConversationChangedNotifyItem

- (instancetype)initWith:(IMAConversationChangedNotifyType)type
{
    if (self = [super init])
    {
        _type = type;
    }
    return self;
}

- (NSNotification *)changedNotification
{
    NSNotification *notify = [NSNotification notificationWithName:[self notificationName] object:self];
    return notify;
}
- (NSString *)notificationName
{
    return [NSString stringWithFormat:@"IMAConversationChangedNotification_%d", (int)_type];
}

@end

@implementation IMAConversationManager


- (instancetype)init
{
    if (self = [super init])
    {
        _conversationList = [[CLSafeSetArray alloc] init];
    }
    return self;
}

- (void)releaseChattingConversation
{
    [_chattingConversation releaseConversation];
    _chattingConversation = nil;
}

- (void)asyncUpdateConversationListComplete
{
    if (_refreshStyle == EIMARefresh_Wait)
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 说明有更新过来，再更新一次
            [self asyncConversationList];
            _refreshStyle = EIMARefresh_None;
        });
    }
    else
    {
        _refreshStyle = EIMARefresh_None;
        [self updateOnLocalMsgComplete];
    }
}
- (void)asyncUpdateUnReadmessageNumb {
    NSInteger unRead = 0;
    
    //    NSMutableArray *conversationList = [NSMutableArray array];
    
    //2.0之前的版本不支持 getConversationList 接口
    NSArray *conversationList = [[TIMManager sharedInstance] getConversationList];
    
    
    for (TIMConversation *conversation in conversationList)
    {
        IMAConversation *conv = nil;
        if ([conversation getType] == TIM_SYSTEM)
        {
#if kSupportCustomConversation
            // 可能返回空
            conv = [[IMACustomConversation alloc] initWith:conversation];
#else
            continue;
#endif
        }
        else
        {
            conv = [[IMAConversation alloc] initWith:conversation];
        }
        
        if (conv )
        {
            if ([[conversation getReceiver] isEqualToString:@"10001"]) {
                
            }else {
                
            }
        }
        
        if (_chattingConversation && [_chattingConversation isEqual:conv])
        {
            // 防止因中途在聊天时，出现onrefresh回调
            _chattingConversation = conv;
        }
        else
        {
            if (conv && [conversation getType] == TIM_C2C)
            {
                unRead += [conversation getUnReadMessageNum];
            }else {
                if ([conversation getType] == TIM_GROUP) {
                    IMAGroup *group = (IMAGroup *)[[IMAPlatformxl sharedInstance].contactMgr getUserByGroupId:[conversation getReceiver]];
                    if ([group isChatGroup]) {
                        
                        unRead += [conversation getUnReadMessageNum];

                    }
                }
            }
        }
    }
    
    
    if (unRead != _unReadMessageCount)
    {
        self.unReadMessageCount = unRead;
    }
    _refreshStyle = EIMARefresh_None;

}

- (void)asyncUpdateConversationList
{
    NSInteger unRead = 0;
    
    //    NSMutableArray *conversationList = [NSMutableArray array];
    
    [self.conversationList removeAllObjects];
    //2.0之前的版本不支持 getConversationList 接口
//    NSArray *conversationList = [[TIMManager sharedInstance] getConversationList];
    
    
//    for (TIMConversation *conversation in conversationList)
//    {
//        IMAConversation *conv = nil;
//        if ([conversation getType] == TIM_SYSTEM)
//        {
//#if kSupportCustomConversation
//            // 可能返回空
//            conv = [[IMACustomConversation alloc] initWith:conversation];
//#else
//            continue;
//#endif
//        }
//        else
//        {
//            conv = [[IMAConversation alloc] initWith:conversation];
//        }
//
//        if (conv )
//        {
//                if ([conversation getType] == TIM_GROUP) {
//                    IMAGroup *group = (IMAGroup *)[[IMAPlatformxl sharedInstance].contactMgr getUserByGroupId:[conversation getReceiver]];
//                    if ([group isChatGroup]) {
//                        if (self.conversationList.count <= 30) {
//                            [self.conversationList addObject:conv];
//                            [self asyncUpdateConversationListComplete];
//
//                        }
//
//                    }
//
//                }else {
//                    if ([[conversation getReceiver] isEqualToString:@"10001"]) {
//                        _refreshStyle = EIMARefresh_None;
//
//                    }else {
//                        if (self.conversationList.count <= 30) {
//
//                    [self.conversationList addObject:conv];
//                    [self asyncUpdateConversationListComplete];
//                        }
//                    }
//            }
//        }
//
//        if (_chattingConversation && [_chattingConversation isEqual:conv])
//        {
//            [conv copyConversationInfo:_chattingConversation];
//            // 防止因中途在聊天时，出现onrefresh回调
//            _chattingConversation = conv;
//        }
//        else
//        {
//            if (conv && [conversation getType] == TIM_C2C)
//            {
//                if (self.conversationList.count <= 30) {
//
//                unRead += [conversation getUnReadMessageNum];
//                }
//            }
//        }
//    }
    
    int cnt = [[TIMManager sharedInstance] ConversationCount];
    
    for (int i = 0; i < cnt && self.conversationList.count <= 50; i++) {
        TIMConversation * conversation = [[TIMManager sharedInstance] getConversationByIndex:i];
        
        IMAConversation *conv = nil;
        if ([conversation getType] == TIM_SYSTEM)
        {
#if kSupportCustomConversation
            // 可能返回空
            conv = [[IMACustomConversation alloc] initWith:conversation];
#else
            continue;
#endif
        }
        else
        {
            conv = [[IMAConversation alloc] initWith:conversation];
        }
        
        if (conv )
        {
            if ([conversation getType] == TIM_GROUP) {
                IMAGroup *group = (IMAGroup *)[[IMAPlatformxl sharedInstance].contactMgr getUserByGroupId:[conversation getReceiver]];
                if ([group isChatGroup]) {
                    if (self.conversationList.count <= 50) {
                        [self.conversationList addObject:conv];
                        [self asyncUpdateConversationListComplete];
                        
                    }
                    
                }
                
            }else {
                if ([[conversation getReceiver] isEqualToString:@"10001"]) {
                    _refreshStyle = EIMARefresh_None;
                    
                }else {
                    if (self.conversationList.count <= 50) {
                    
                        [self.conversationList addObject:conv];
                        [self asyncUpdateConversationListComplete];
                    }
                }
            }
        }
        
        if (_chattingConversation && [_chattingConversation isEqual:conv])
        {
            [conv copyConversationInfo:_chattingConversation];
            // 防止因中途在聊天时，出现onrefresh回调
            _chattingConversation = conv;
        }
        else
        {
            if (conv && [conversation getType] == TIM_C2C)
            {
                if (self.conversationList.count <= 50) {
                
                    unRead += [conversation getUnReadMessageNum];
                }
            }
        }

    }

    if (unRead != _unReadMessageCount)
    {
        self.unReadMessageCount = unRead;
    }
    DebugLog(@"==========>>>>>>>>>asyncUpdateConversationList Complete");
}

- (void)asyncConversationList
{
    DebugLog(@"==========>>>>>>>>>asyncConversationList");
    // 因OnRefresh里面不定期有回调，能过这种处理，避免_conversationList修改导致界面Crash
    if (_refreshStyle == EIMARefresh_None)
    {
        _refreshStyle = EIMARefresh_ING;
        [self asyncUpdateConversationList];
    }
    else
    {
        _refreshStyle = EIMARefresh_Wait;
    }
}

- (void)addConversationChangedObserver:(id)observer handler:(SEL)selector forEvent:(NSUInteger)eventID
{
    NSUInteger op = EIMAContact_AddNewSubGroup;
    do
    {
        if (op & eventID)
        {
            NSString *notification = [NSString stringWithFormat:@"IMAConversationChangedNotification_%d", (int)op];
            [[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:notification object:nil];
            eventID -= op;
        }
        op = op << 1;
        
    } while (eventID > 0);
}

- (void)removeConversationChangedObser:(id)observer
{
    [[NSNotificationCenter defaultCenter] removeObserver:observer];
}

- (void)deleteConversation:(IMAConversation *)conv needUIRefresh:(BOOL)need
{
    NSInteger index = [_conversationList indexOfObject:conv];
    if (index >= 0 && index < [_conversationList count])
    {
        [conv setReadAllMsg];
        self.unReadMessageCount -= [conv unReadCount];
        [_conversationList removeObject:conv];
        
        if ([conv type] == TIM_C2C)
        {
            [[TIMManager sharedInstance] deleteConversation:[conv type] receiver:[conv receiver]];
        }
        else if ([conv type] == TIM_GROUP)
        {
            [[TIMManager sharedInstance] deleteConversationAndMessages:[conv type] receiver:[conv receiver]];
        }
        
        if (need)
        {
            [self updateOnDelete:conv atIndex:index];
        }
    }
}
- (IMAConversation *)groupChatWith:(NSString *)user {
    TIMConversation *conv = nil;
    conv = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:user];
    NSLog(@"vvvvvvvmmmm == %@",conv);
    if (conv)
    {
        IMAConversation *temp = [[IMAConversation alloc] initWith:conv];
        
        //        NSInteger index = [_conversationList indexOfObject:temp];
        //        if (index >= 0 && index < _conversationList.count)
        //        {
        //            IMAConversation *ret = [_conversationList objectAtIndex:index];
        //            _chattingConversation = ret;
        //            return ret;
        //        }
        
        _chattingConversation = temp;
        return temp;
        
    }
    return nil;
    
}
- (IMAConversation *)msgchatWith:(IMAUser *)user
{
    TIMConversation *conv = nil;
    if ([user isC2CType])
    {
        conv = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:[user userId]];
    }
    else if([user isGroupType])
    {
        conv = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:[(IMAGroup *)user userId]];
    }
    else if ([user isSystemType])
    {
        // 暂不支持System消息
        return nil;
    }
    
//    self.unReadMessageCount -= [conv getUnReadMessageNum];
    
    //    [conv setReadMessage];
//    [conv setReadMessage:nil succ:^{
//        
//    } fail:^(int code, NSString *msg) {
//        
//    }];
    
    if (conv)
    {
        IMAConversation *temp = [[IMAConversation alloc] initWith:conv];
        
        NSInteger index = [_conversationList indexOfObject:temp];
        if (index >= 0 && index < _conversationList.count)
        {
            IMAConversation *ret = [_conversationList objectAtIndex:index];
            _chattingConversation = ret;
            _chattingConversation.lastMessage = _chattingConversation.lastMessage;
            return ret;
        }
        
        _chattingConversation = temp;
        return temp;
    }
    return nil;
}

- (IMAConversation *)chatWith:(NSString *)user
{
    TIMConversation *conv = nil;
    //    if ([user isC2CType])
    //    {
    conv = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:user];
    //    }
    //    else if([user isGroupType])
    //    {
    //        conv = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:[user userId]];
    //    }
    //    else if ([user isSystemType])
    //    {
    //        // 暂不支持System消息
    //        return nil;
    //    }
    
//    self.unReadMessageCount -= [conv getUnReadMessageNum];
//    [conv setReadMessage];
    
    if (conv)
    {
        IMAConversation *temp = [[IMAConversation alloc] initWith:conv];
        
        NSInteger index = [_conversationList indexOfObject:temp];
        if (index >= 0 && index < _conversationList.count)
        {
            IMAConversation *ret = [_conversationList objectAtIndex:index];
            _chattingConversation = ret;
            _chattingConversation.lastMessage = _chattingConversation.lastMessage;
            return ret;
        }
        
        _chattingConversation = temp;
        return temp;
    }
    return nil;
}

// 主用要于自定义类型
- (IMAConversation *)queryConversationWithType:(IMAConType)user
{
    //    for (NSInteger i = 0; i < [_conversationList count]; i++)
    //    {
    //        IMAConversation *conv = [_conversationList objectAtIndex:i];
    //        if ([conv isChatWith:user])
    //        {
    //            return conv;
    //        }
    //    }
    return nil;
}

- (IMAConversation *)queryConversationWith:(IMAUser *)user
{
    if (user)
    {
        for (NSInteger i = 0; i < [_conversationList count]; i++)
        {
            IMAConversation *conv = [_conversationList objectAtIndex:i];
            if ([conv isChatWith:user])
            {
                return conv;
            }
        }
    }
    return nil;
}

- (void)removeConversationWith:(IMAUser *)user
{
    for (NSInteger i = 0; i < [_conversationList count]; i++)
    {
        IMAConversation *conv = [_conversationList objectAtIndex:i];
        TIMConversationType type;
        if ([user isKindOfClass:[IMAGroup class]]) {
            type = TIM_GROUP;
        }else {
            type = TIM_C2C;

        }
        if ([conv isChatWith:user] && [conv type] == type)
        {
            if (conv == _chattingConversation)
            {
                // TODO:通知界面
            }
            [_conversationList removeObjectAtIndex:i];
            self.unReadMessageCount -= [conv unReadCount];
            
            if ([conv type] == TIM_C2C)
            {
                [[TIMManager sharedInstance] deleteConversation:[conv type] receiver:[conv receiver]];
            }
            else if ([conv type] == TIM_GROUP)
            {
                [[TIMManager sharedInstance] deleteConversationAndMessages:[conv type] receiver:[conv receiver]];
            }
            
            [self updateOnDelete:conv atIndex:i];
            break;
        }
    }
}

//- (void)removeConversationWithConv:(IMAConversation *)conv
//{
//    if (conv == nil)
//    {
//        return;
//    }
//    [[TIMManager sharedInstance] deleteConversation:[conv type] receiver:[conv receiver]];
//}

- (void)updateConversationWith:(IMAUser *)user
{
    IMAConversation *conv = [self queryConversationWith:user];
    if (conv)
    {
        [self updateOnConversationChanged:conv];
    }
}

- (NSInteger)insertPosition
{
//    IMAPlatformxl *mp = [IMAPlatformxl sharedInstance];
//    if (!mp.isConnected)
//    {
//        return 1;
//    }
    return 0;
}


/**
 *  新消息通知
 *
 *  @param msgs 新消息列表，TIMMessage 类型数组
 */
- (void)onNewMessage:(NSArray *)msgs
{
    
    for (TIMMessage *msg in msgs)
    {
        IMAMsg *imamsg = [IMAMsg msgWith:msg];
        TIMElem *elemddd = [msg getElem:0];
        TIMConversation *convcc = [msg getConversation];
        
        if ([elemddd isKindOfClass:[TIMGroupTipsElem class]])
        {
            TIMGroupTipsElem * GroupTips = (TIMGroupTipsElem *)elemddd;
            //邀请加入群/退出群/踢出群(收到群组ID-10086)
            if ([GroupTips.group isEqualToString:@"10086"]) {
                if (GroupTips.type == TIM_GROUP_TIPS_TYPE_INVITE||GroupTips.type == TIM_GROUP_TIPS_TYPE_QUIT_GRP||GroupTips.type == TIM_GROUP_TIPS_TYPE_KICKED){
                    
                    [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"OrderRefresh" object:nil] postingStyle:NSPostWhenIdle];
                }
                if (GroupTips.type == TIM_GROUP_TIPS_TYPE_INVITE) {
                    
                    [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"JoinOrderRefresh" object:nil] postingStyle:NSPostWhenIdle];
                }
                if (GroupTips.type == TIM_GROUP_TIPS_TYPE_QUIT_GRP||GroupTips.type == TIM_GROUP_TIPS_TYPE_KICKED) {
                    TIMUserProfile * userProfile = GroupTips.opUserInfo;
                    [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"QuitOrderRefresh" object:userProfile.identifier] postingStyle:NSPostWhenIdle];
                }
                return;
            }
        }
        BOOL messageType = [convcc getType] == TIM_GROUP;
        BOOL isSystem = [convcc getType] == TIM_SYSTEM;
        BOOL isC2C    = [convcc getType] == TIM_C2C;
        if (messageType) {
            if ([elemddd isKindOfClass:[TIMCustomElem class]]) {
                TIMCustomElem *elem = (TIMCustomElem *)[msg getElem:0];
                if ([elem.ext isEqualToString:@"CallOrderExt"] || [elem.desc isEqualToString:@"CallOrderExt"]) {
                    [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"CallOrderExt" object:msg] postingStyle:NSPostWhenIdle];
                    return;
                }
            }
        }
        if (isC2C) {
            if ([elemddd isKindOfClass:[TIMCustomElem class]]) {
                TIMCustomElem *elem = (TIMCustomElem *)[msg getElem:0];
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:elem.data options:0 error:nil];
                BMHLog(@"jieshou111%@",dic);
                if([SafeStr([dic objectForKey:@"cmd"]) isEqualToString:@"10001"])
                {
                    //提示余额不足
                    KPostNotification(KInsufficientBalance, nil);
                }
                
                if (![dic[@"giftBubbleImage"]isKindOfClass:[NSNull class]] && [dic[@"giftBubbleImage"] length] > 0){
                    NSDictionary *dictemp;
                    if(![dic[@"giftId"]isKindOfClass:[NSNull class]] && dic[@"giftId"] != nil){
//                        if ([dic[@""]integerValue ] == 0) {
//                            NSNotification *notification2 =[NSNotification notificationWithName:@"chatGiftMessage" object:imamsg userInfo:nil];
//                            [[NSNotificationCenter defaultCenter] postNotification:notification2];
//                        }else{
                            dictemp  = @{@"giftBubbleImage":dic[@"giftBubbleImage"],@"giftId":dic[@"giftId"]};
                            NSNotification *notification =[NSNotification notificationWithName:@"videoGiftMessage" object:imamsg userInfo:nil];
                            [[NSNotificationCenter defaultCenter] postNotification:notification];
//                        }
                        
                    }else{
                        dictemp  = @{@"giftBubbleImage":dic[@"giftBubbleImage"],@"giftId":@"-1"};
                    }
                   
//                    [msg remove];
                    return;
                }
                if ([[dic objectForKey:@"action"]integerValue] == 9) {
                    NSNotification *notification =[NSNotification notificationWithName:@"ChatThemeAndQuestion" object:nil userInfo:dic];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                    [msg remove];
                    return;
                }
                if ([elem.ext isEqualToString:@"callcommand"] && [[dic objectForKey:@"cmd"]isEqualToString:@"10000"]) {
                    [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"hangupYuebuzu" object:msg] postingStyle:NSPostWhenIdle];
                    NSLog(@"%@", dic[@"cmd"]);
                    BMHLog(@"hangupYuebuzu");
                    [msg remove];
                    return;
                }
                 if ([elem.ext isEqualToString:@"OrderNotifyExt"] || [elem.desc isEqualToString:@"OrderNotifyExt"]) {
//                     [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"OrderNotifyExt" object:msg] postingStyle:NSPostWhenIdle];
//                     return;
                     if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
                         return;
                     }
                     if([[XLAccountManager shareInstance].model.IsAnchor isEqualToString:@"1"])
                     {
                         return;
                     }
                     XLIMViewModel * viewModel = [[XLIMViewModel alloc]init];
                     [viewModel getOrderListComplete:^(NSArray *data) {
                         if(data.count > 0)
                         {
                             //一天内拒绝次数大于2 则不弹出
                             NSDictionary * dict = [kUserDefaults objectForKey:KRefuseVideoChatNum];
                             NSInteger num = [dict[@"num"] integerValue];
                             NSInteger time = [dict[@"time"] integerValue];
                             if(num >= 5)
                             {
                                 if([[kUtilityClass getNowTimeTimestamp] integerValue] - time > 24 * 3600)
                                 {//时间大于一天
                                     NSDictionary * params = @{@"num":@"0",
                                                               @"time":[kUtilityClass getNowTimeTimestamp]
                                                               };
                                     [kUserDefaults setObject:params forKey:KRefuseVideoChatNum];
                                     [kUserDefaults synchronize];
                                 }else
                                 {
                                     return;
                                 }
                             }
                             
                             
                             int x = arc4random() % data.count;
                             XLOrderPeopleModel * model =data[x];
                             if ([[self getCurrentUIVC] isKindOfClass:[CallRecvViewController class]] || [[self getCurrentUIVC] isKindOfClass:[CallMakeViewController class]] || [[self getCurrentUIVC] isKindOfClass:[XLV2LoginViewController class]] || [[self getCurrentUIVC] isKindOfClass:[XLMakeVoiceChatVC class]] || [[self getCurrentUIVC] isKindOfClass:[XLRecVoiceChatVC class]]) {
                                 return;
                             }
                             //接听超时
                             if ([[NSDate date] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSinceNow:[model.CreateTime doubleValue]]] > 60) {
                                 return;
                             }
                             [[[UIApplication sharedApplication].keyWindow viewWithTag:1234567890] removeFromSuperview];
                             [[[UIApplication sharedApplication].keyWindow viewWithTag:100000000] removeFromSuperview];
                             if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
                                 CallRecvViewController *call = [[CallRecvViewController alloc] init];//接听
                                 NSDictionary * dict = @{@"name":model.NickName,
                                                         @"headimg":model.ImgUrl,
                                                         @"userid":model.UserId,
                                                         @"videoUrl":model.VideoUrl
                                                         };
                                 PeerModel * peermodel = [PeerModel modelWithDictionary:dict];
                                 call.peermodel = peermodel;
                                 call.isShowView = YES;
//                                 [kAppWindow bringSubviewToFront:call];
                                 kWeakSelf(self);
                                 call.skipBlock = ^(HomeCallModel *model, NSError *error) {
                                     if(!error)
                                     {
                                     }else
                                     {
                                         if (error.code == 6) {  //余额不足
                                             [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
                                             TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
                                             topVC.In_purchase = isIn_purchase;
                                             [[weakself getCurrentUIVC].navigationController pushViewController:topVC animated:YES];
                                         } else {  //被拉入黑名单//对方已屏蔽视聊
                                             [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
                                         }
                                     }
                                 };
                                 UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:call];
                                 [[weakself getCurrentUIVC] presentViewController:nav animated:YES completion:nil];
                             }
                         }

                     }];
                     
                     [msg remove];
                     return;
                 }}}

        if (messageType || isSystem) {
            
            if ([elemddd isKindOfClass:[TIMCustomElem class]]) {
                TIMCustomElem *elem = (TIMCustomElem *)[msg getElem:0];
                
                if ([elem.ext isEqualToString:@"CallNotification"] || [elem.desc isEqualToString:@"CallNotification"]) {
//                    [self paraseCallMessage:imamsg];
                }else {
                    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
                    if (elemCmd.action > 0 && elemCmd.action < 9)  {
                        TIMConversation *conv = [msg getConversation];
                        
                        BOOL isSystemMsg = [conv getType] == TIM_SYSTEM;
                        
                        BOOL isAddGroupReq = NO;
                        BOOL isAddFriendReq = NO;
                        BOOL isContinue = YES;
                        if (isSystemMsg)
                        {
                            int elemCount = [msg elemCount];
                            for (int i = 0; i < elemCount; i++)
                            {
                                TIMElem* elem = [msg getElem:i];
                                if ([elem isKindOfClass:[TIMGroupSystemElem class]])
                                {
                                    TIMGroupSystemElem *gse = (TIMGroupSystemElem *)elem;
                                    if (gse.type == TIM_GROUP_SYSTEM_ADD_GROUP_REQUEST_TYPE)
                                    {
                                        isContinue = NO;
                                        isAddGroupReq = YES;
                                    }
                                }
                                else if ([elem isKindOfClass:[TIMSNSSystemElem class]])
                                {
                                    TIM_SNS_SYSTEM_TYPE type = ((TIMSNSSystemElem *)elem).type;
                                    if (type == TIM_SNS_SYSTEM_ADD_FRIEND_REQ)
                                    {
                                        if (!msg.isSelf)
                                        {
                                            isContinue = NO;
                                            isAddFriendReq = YES;
                                        }
                                    }
                                }
                            }
                            if (isContinue)
                            {
                                continue;
                            }
                        }
                        
                        BOOL updateSucc = NO;
                        
                        for (int i = 0; i < [_conversationList count]; i++)
                        {
                            IMAConversation *imaconv = [_conversationList objectAtIndex:i];
                            NSString *imaconvReceiver = [imaconv receiver];
                            if (imaconv.type == [conv getType] && ([imaconvReceiver isEqualToString:[conv getReceiver]] || [imaconvReceiver isEqualToString:[IMACustomConversation getCustomConversationID:imamsg]]))
                            {
                                if (imaconv.conversation == _chattingConversation.conversation)
                                {
                                    //如果是c2c会话，则更新“对方正在输入...”状态
                                    BOOL isInputStatus = NO;
                                    
                                    if (!msg.isSelf)
                                    {
                                        if ([_chattingConversation imaType] == TIM_C2C)
                                        {
                                            int elemCount = [imamsg.msg elemCount];
                                            for (int i = 0; i < elemCount; i++)
                                            {
                                                TIMElem* elem = [msg getElem:i];
                                                CustomElemCmd *elemCmd = [self isOnlineMsg:elem];
                                                
                                                if (elemCmd)
                                                {
                                                    isInputStatus = YES;
                                                    [[NSNotificationCenter defaultCenter] postNotificationName:kUserInputStatus object:elemCmd];
                                                }
                                            }
                                        }
                                        
                                        if (!isInputStatus)
                                        {
                                            //                            [conv setReadMessage];
                                            imaconv.lastMessage = imamsg;
                                            [_chattingConversation onReceiveNewMessage:imamsg];
                                        }
                                    }
                                }
                                else
                                {
                                    TIMElem* elem = [msg getElem:0];
                                    CustomElemCmd *elemCmd = [self isOnlineMsg:elem];
                                    
                                    if (!elemCmd)
                                    {
                                        imaconv.lastMessage = imamsg;
                                        if (isSystemMsg)
                                        {
                                            __weak IMAConversationManager *ws = self;
                                            // 系统消息
                                            IMACustomConversation *customConv = (IMACustomConversation *)imaconv;
                                            [customConv saveMessage:imamsg succ:^(int newUnRead) {
                                                ws.unReadMessageCount += newUnRead;
                                                [ws updateOnChat:imaconv moveFromIndex:i];
                                            }];
                                        }
                                        else
                                        {
                                            //如果是自己发出去的消息，一定是已读(这里判断主要是用在多终端登录的情况下)
                                            if (![imamsg isMineMsg])
                                            {
                                                self.unReadMessageCount++;
                                            }
                                            [self updateOnChat:imaconv moveFromIndex:i];
                                        }
                                    }
                                }
                                updateSucc = YES;
                                break;
                            }
                        }
                        
                        if (!updateSucc && _refreshStyle == EIMARefresh_None)
                        {
                            if (isSystemMsg)
                            {

                            }
                            else
                            {
                                [[TIMGroupManager sharedInstance] GetGroupInfo:@[[conv getReceiver]] succ:^(NSArray *arr) {
                                    TIMGroupInfo *groupInfo = arr[0];
                                    
                                    if ([[groupInfo groupType] isEqualToString: @"Private"]) {
                                        IMAConversation *temp = [[IMAConversation alloc] initWith:conv];
                                        
                                        if (![_conversationList containsObject:temp]) {
                                            // 说明会话列表中没有该会话，新生建会话，并更新到
                                            temp.lastMessage = imamsg;
                                            [_conversationList insertObject:temp atIndex:[self insertPosition]];
                                            self.unReadMessageCount++;
                                            [self updateOnNewConversation:temp];
                                            
                                        }else {
                                            [_chattingConversation onReceiveNewMessage:imamsg];
                                            
                                        }
                                        
                                    }else {
                                        [_chattingConversation onReceiveNewMessage:imamsg];
                                        
                                    }
                                    
                                } fail:^(int code, NSString *msg) {
                                    [_chattingConversation onReceiveNewMessage:imamsg];
                                    
                                }];
                                
                                
                            }
                        }

                    }else {
                        
                    }
                }
            }else {
                TIMConversation *conv = [msg getConversation];
                
                BOOL isSystemMsg = [conv getType] == TIM_SYSTEM;
                
                BOOL isAddGroupReq = NO;
                BOOL isAddFriendReq = NO;
                BOOL isContinue = YES;
                if (isSystemMsg)
                {
                    int elemCount = [msg elemCount];
                    for (int i = 0; i < elemCount; i++)
                    {
                        TIMElem* elem = [msg getElem:i];
                        if ([elem isKindOfClass:[TIMGroupSystemElem class]])
                        {
                            TIMGroupSystemElem *gse = (TIMGroupSystemElem *)elem;
                            if (gse.type == TIM_GROUP_SYSTEM_ADD_GROUP_REQUEST_TYPE)
                            {
                                isContinue = NO;
                                isAddGroupReq = YES;
                            }
                        }
                        else if ([elem isKindOfClass:[TIMSNSSystemElem class]])
                        {
                            TIM_SNS_SYSTEM_TYPE type = ((TIMSNSSystemElem *)elem).type;
                            if (type == TIM_SNS_SYSTEM_ADD_FRIEND_REQ)
                            {
                                if (!msg.isSelf)
                                {
                                    isContinue = NO;
                                    isAddFriendReq = YES;
                                }
                            }
                        }
                    }
                    if (isContinue)
                    {
                        continue;
                    }
                }
                
                BOOL updateSucc = NO;
                
                for (int i = 0; i < [_conversationList count]; i++)
                {
                    IMAConversation *imaconv = [_conversationList objectAtIndex:i];
                    NSString *imaconvReceiver = [imaconv receiver];
                    if (imaconv.type == [conv getType] && ([imaconvReceiver isEqualToString:[conv getReceiver]] || [imaconvReceiver isEqualToString:[IMACustomConversation getCustomConversationID:imamsg]]))
                    {
                        if (imaconv.conversation == _chattingConversation.conversation)
                        {
                            //如果是c2c会话，则更新“对方正在输入...”状态
                            BOOL isInputStatus = NO;
                            
                            if (!msg.isSelf)
                            {
                                if ([_chattingConversation imaType] == TIM_C2C)
                                {
                                    int elemCount = [imamsg.msg elemCount];
                                    for (int i = 0; i < elemCount; i++)
                                    {
                                        TIMElem* elem = [msg getElem:i];
                                        CustomElemCmd *elemCmd = [self isOnlineMsg:elem];
                                        
                                        if (elemCmd)
                                        {
                                            isInputStatus = YES;
                                            [[NSNotificationCenter defaultCenter] postNotificationName:kUserInputStatus object:elemCmd];
                                        }
                                    }
                                }
                                
                                if (!isInputStatus)
                                {
                                    //                            [conv setReadMessage];
                                    imaconv.lastMessage = imamsg;
                                    [_chattingConversation onReceiveNewMessage:imamsg];
                                }
                            }
                        }
                        else
                        {
                            TIMElem* elem = [msg getElem:0];
                            CustomElemCmd *elemCmd = [self isOnlineMsg:elem];
                            
                            if (!elemCmd)
                            {
                                imaconv.lastMessage = imamsg;
                                if (isSystemMsg)
                                {
                                    __weak IMAConversationManager *ws = self;
                                    // 系统消息
                                    IMACustomConversation *customConv = (IMACustomConversation *)imaconv;
                                    [customConv saveMessage:imamsg succ:^(int newUnRead) {
                                        ws.unReadMessageCount += newUnRead;
                                        [ws updateOnChat:imaconv moveFromIndex:i];
                                    }];
                                }
                                else
                                {
                                    //如果是自己发出去的消息，一定是已读(这里判断主要是用在多终端登录的情况下)
                                    if (![imamsg isMineMsg])
                                    {
                                        self.unReadMessageCount++;
                                    }
                                    [self updateOnChat:imaconv moveFromIndex:i];
                                }
                            }
                        }
                        updateSucc = YES;
                        break;
                    }
                }
                
                if (!updateSucc && _refreshStyle == EIMARefresh_None)
                {
                    if (isSystemMsg)
                    {
                        //                    NSString *receiverid = [IMACustomConversation getCustomConversationID:imamsg];
                        //                    TIMConversation *imconv = [[TIMManager sharedInstance] getConversation:TIM_SYSTEM receiver:receiverid];
                        //                    [imconv setReadMessage:nil succ:^{
                        //
                        //                    } fail:^(int code, NSString *msg) {
                        //
                        //                    }];
                        //                    // 说明会话列表中没有该会话，新生建会话，并更新到
                        //                    IMACustomConversation *temp = [[IMACustomConversation alloc] initWith:imconv andMsg:imamsg];
                        //                    if (temp)
                        //                    {
                        //                        __weak IMAConversationManager *ws = self;
                        //                        [temp saveMessage:imamsg succ:^(int newUnRead) {
                        //                            ws.unReadMessageCount += newUnRead;
                        //                        }];
                        //                        [_conversationList insertObject:temp atIndex:[self insertPosition]];
                        //                        [self updateOnNewConversation:temp];
                        //                    }
                    }
                    else
                    {
                        [[TIMGroupManager sharedInstance] GetGroupInfo:@[[conv getReceiver]] succ:^(NSArray *arr) {
                            TIMGroupInfo *groupInfo = arr[0];
                            
                            if ([[groupInfo groupType] isEqualToString: @"Private"]) {
                                IMAConversation *temp = [[IMAConversation alloc] initWith:conv];
                                
                                if (![_conversationList containsObject:temp]) {
                                    // 说明会话列表中没有该会话，新生建会话，并更新到
                                    temp.lastMessage = imamsg;
                                    [_conversationList insertObject:temp atIndex:[self insertPosition]];
                                    self.unReadMessageCount++;
                                    [self updateOnNewConversation:temp];
                                    
                                }else {
                                    [_chattingConversation onReceiveNewMessage:imamsg];
                                    
                                }
                                
                            }else {
                                [_chattingConversation onReceiveNewMessage:imamsg];
                                
                            }
                            
                        } fail:^(int code, NSString *msg) {
                            [_chattingConversation onReceiveNewMessage:imamsg];
                            
                        }];
                        
                        
                    }
                }

            }
       

        }else {

        if ([elemddd isKindOfClass:[TIMCustomElem class]]) {
            TIMCustomElem *elem = (TIMCustomElem *)[msg getElem:0];
            TIMOfflinePushInfo *pushinfo = [msg getOfflinePushInfo];
            if ([elem.ext isEqualToString:@"QiangDanNotification"] || [elem.desc isEqualToString:@"QiangDanNotification"]) {
                [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"CallOrderExt" object:msg] postingStyle:NSPostWhenIdle];
                [msg remove];
                return;
            }else {
                CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
                if (elemCmd.action == 12) {
                    [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"ontherPersonCause" object:nil] postingStyle:NSPostWhenIdle];
                }
                if (elemCmd.action > 0 && elemCmd.action < 9) {
                    if (elemCmd.action == 6) {
                        [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"ontherPersonCause" object:nil] postingStyle:NSPostWhenIdle];
                    }
                    if (elemCmd.action == 8) {
                        TIMConversation *conv = [msg getConversation];
                        NSString *userId = [conv getReceiver];
                        [[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:@"inviteVideoChatMessage" object:userId] postingStyle:NSPostWhenIdle];
                    }
                    TIMConversation *conv = [msg getConversation];
                    
                    BOOL isSystemMsg = [conv getType] == TIM_SYSTEM;
                    
                    BOOL isAddGroupReq = NO;
                    BOOL isAddFriendReq = NO;
                    BOOL isContinue = YES;
                    if (isSystemMsg)
                    {
                        int elemCount = [msg elemCount];
                        for (int i = 0; i < elemCount; i++)
                        {
                            TIMElem* elem = [msg getElem:i];
                            if ([elem isKindOfClass:[TIMGroupSystemElem class]])
                            {
                                TIMGroupSystemElem *gse = (TIMGroupSystemElem *)elem;
                                if (gse.type == TIM_GROUP_SYSTEM_ADD_GROUP_REQUEST_TYPE)
                                {
                                    isContinue = NO;
                                    isAddGroupReq = YES;
                                }
                            }
                            else if ([elem isKindOfClass:[TIMSNSSystemElem class]])
                            {
                                TIM_SNS_SYSTEM_TYPE type = ((TIMSNSSystemElem *)elem).type;
                                if (type == TIM_SNS_SYSTEM_ADD_FRIEND_REQ)
                                {
                                    if (!msg.isSelf)
                                    {
                                        isContinue = NO;
                                        isAddFriendReq = YES;
                                    }
                                }
                            }
                        }
                        if (isContinue)
                        {
                            continue;
                        }
                    }
                    
                    BOOL updateSucc = NO;
                    
                    for (int i = 0; i < [_conversationList count]; i++)
                    {
                        IMAConversation *imaconv = [_conversationList objectAtIndex:i];
                        NSString *imaconvReceiver = [imaconv receiver];
                        if (imaconv.type == [conv getType] && ([imaconvReceiver isEqualToString:[conv getReceiver]] || [imaconvReceiver isEqualToString:[IMACustomConversation getCustomConversationID:imamsg]]))
                        {
                            if (imaconv.conversation == _chattingConversation.conversation)
                            {
                                //如果是c2c会话，则更新“对方正在输入...”状态
                                BOOL isInputStatus = NO;
                                
                                if (!msg.isSelf)
                                {
                                    //                                                if ([_chattingConversation imaType] == TIM_C2C)
                                    //                                                {
                                    //                                                    int elemCount = [imamsg.msg elemCount];
                                    //                                                    for (int i = 0; i < elemCount; i++)
                                    //                                                    {
                                    //                                                        TIMElem* elem = [msg getElem:i];
                                    //                                                        CustomElemCmd *elemCmd = [self isOnlineMsg:elem];
                                    //
                                    //                                                        if (elemCmd)
                                    //                                                        {
                                    //                                                            isInputStatus = YES;
                                    //                                                            [[NSNotificationCenter defaultCenter] postNotificationName:kUserInputStatus object:elemCmd];
                                    //                                                        }
                                    //                                                    }
                                    //                                                }
                                    
                                    if (!isInputStatus)
                                    {
                                        [conv setReadMessage];
                                        imaconv.lastMessage = imamsg;
                                        [_chattingConversation onReceiveNewMessage:imamsg];
                                        [[NSNotificationCenter defaultCenter] postNotificationName:kUserInputStatus object:imamsg];
                                        
                                    }
                                }
                            }
                            else
                            {
                                //                                        TIMElem* elem = [msg getElem:0];
                                //                                        CustomElemCmd *elemCmd = [self isOnlineMsg:elem];
                                //
                                //                    if (!elemCmd)
                                //                    {
                                imaconv.lastMessage = imamsg;
                                
                                if (isSystemMsg)
                                {
                                    __weak IMAConversationManager *ws = self;
                                    // 系统消息
                                    IMACustomConversation *customConv = (IMACustomConversation *)imaconv;
                                    [customConv saveMessage:imamsg succ:^(int newUnRead) {
                                        ws.unReadMessageCount += newUnRead;
                                        [ws updateOnChat:imaconv moveFromIndex:i];
                                    }];
                                }
                                else
                                {
                                    //如果是自己发出去的消息，一定是已读(这里判断主要是用在多终端登录的情况下)
                                    if (![imamsg isMineMsg])
                                    {
                                        self.unReadMessageCount++;
                                    }
                                    [self updateOnChat:imaconv moveFromIndex:i];
                                }
                            }
                            //                }
                            updateSucc = YES;
                            break;
                        }
                    }
                    
                    if (!updateSucc && _refreshStyle == EIMARefresh_None)
                    {
                        if (isSystemMsg)
                        {
                            //                NSString *receiverid = [IMACustomConversation getCustomConversationID:imamsg];
                            //                TIMConversation *imconv = [[TIMManager sharedInstance] getConversation:TIM_SYSTEM receiver:receiverid];
                            //                [imconv setReadMessage];
                            //                // 说明会话列表中没有该会话，新生建会话，并更新到
                            //                IMACustomConversation *temp = [[IMACustomConversation alloc] initWith:imconv andMsg:imamsg];
                            //                if (temp)
                            //                {
                            //                    __weak IMAConversationManager *ws = self;
                            //                    [temp saveMessage:imamsg succ:^(int newUnRead) {
                            //                        ws.unReadMessageCount += newUnRead;
                            //                    }];
                            //                    [_conversationList insertObject:temp atIndex:[self insertPosition]];
                            //                    [self updateOnNewConversation:temp];
                            //                }
                            [msg remove];
                            
                        }
                        else
                        {
                            // 说明会话列表中没有该会话，新生建会话，并更新到
                            IMAConversation *temp = [[IMAConversation alloc] initWith:conv];
                            temp.lastMessage = imamsg;
                            NSLog(@"fffmmmmm == %ld --- %ld",_conversationList.count,[self insertPosition] );
                            if ([[convcc getReceiver] isEqualToString:@"10001"]) {
                                [[NSNotificationCenter defaultCenter] postNotificationName:@"pingkuntongzhi" object:imamsg];
                                
                            }else {
                                [_conversationList insertObject:temp atIndex:[self insertPosition]];
                                
                                [self updateOnNewConversation:temp];
                                
                            }
                            self.unReadMessageCount++;
                        }
                    }
                    
                    
                }else {
                    if (elemCmd.action != 12) {
                        [msg remove];
                    }
                    
                }

            }
        }else {
            TIMConversation *conv = [msg getConversation];
            
            BOOL isSystemMsg = [conv getType] == TIM_SYSTEM;
            
            BOOL isAddGroupReq = NO;
            BOOL isAddFriendReq = NO;
            BOOL isContinue = YES;
            if (isSystemMsg)
            {
                int elemCount = [msg elemCount];
                for (int i = 0; i < elemCount; i++)
                {
                    TIMElem* elem = [msg getElem:i];
                    if ([elem isKindOfClass:[TIMGroupSystemElem class]])
                    {
                        TIMGroupSystemElem *gse = (TIMGroupSystemElem *)elem;
                        if (gse.type == TIM_GROUP_SYSTEM_ADD_GROUP_REQUEST_TYPE)
                        {
                            isContinue = NO;
                            isAddGroupReq = YES;
                        }
                    }
                    else if ([elem isKindOfClass:[TIMSNSSystemElem class]])
                    {
                        TIM_SNS_SYSTEM_TYPE type = ((TIMSNSSystemElem *)elem).type;
                        if (type == TIM_SNS_SYSTEM_ADD_FRIEND_REQ)
                        {
                            if (!msg.isSelf)
                            {
                                isContinue = NO;
                                isAddFriendReq = YES;
                            }
                        }
                    }
                }
                if (isContinue)
                {
                    continue;
                }
            }
            
            BOOL updateSucc = NO;
            
            for (int i = 0; i < [_conversationList count]; i++)
            {
                IMAConversation *imaconv = [_conversationList objectAtIndex:i];
                NSString *imaconvReceiver = [imaconv receiver];
                if (imaconv.type == [conv getType] && ([imaconvReceiver isEqualToString:[conv getReceiver]] || [imaconvReceiver isEqualToString:[IMACustomConversation getCustomConversationID:imamsg]]))
                {
                    if (imaconv.conversation == _chattingConversation.conversation)
                    {
                        //如果是c2c会话，则更新“对方正在输入...”状态
                        BOOL isInputStatus = NO;
                        
                        if (!msg.isSelf)
                        {
                            //                                                if ([_chattingConversation imaType] == TIM_C2C)
                            //                                                {
                            //                                                    int elemCount = [imamsg.msg elemCount];
                            //                                                    for (int i = 0; i < elemCount; i++)
                            //                                                    {
                            //                                                        TIMElem* elem = [msg getElem:i];
                            //                                                        CustomElemCmd *elemCmd = [self isOnlineMsg:elem];
                            //
                            //                                                        if (elemCmd)
                            //                                                        {
                            //                                                            isInputStatus = YES;
                            //                                                            [[NSNotificationCenter defaultCenter] postNotificationName:kUserInputStatus object:elemCmd];
                            //                                                        }
                            //                                                    }
                            //                                                }
                            
                            if (!isInputStatus)
                            {
                                if ([[convcc getReceiver] isEqualToString:@"10001"]) {
                                    
                                }else {
                                  [conv setReadMessage];

                                }
                                imaconv.lastMessage = imamsg;
                                [_chattingConversation onReceiveNewMessage:imamsg];
                                [[NSNotificationCenter defaultCenter] postNotificationName:kUserInputStatus object:imamsg];
                                
                            }
                        }
                    }
                    else
                    {
                        //                                        TIMElem* elem = [msg getElem:0];
                        //                                        CustomElemCmd *elemCmd = [self isOnlineMsg:elem];
                        //
                        //                    if (!elemCmd)
                        //                    {
                        imaconv.lastMessage = imamsg;
                        if (isSystemMsg)
                        {
                            __weak IMAConversationManager *ws = self;
                            // 系统消息
                            IMACustomConversation *customConv = (IMACustomConversation *)imaconv;
                            [customConv saveMessage:imamsg succ:^(int newUnRead) {
                                    ws.unReadMessageCount += newUnRead;
                                [ws updateOnChat:imaconv moveFromIndex:i];
                            }];
                        }
                        else
                        {
                            //如果是自己发出去的消息，一定是已读(这里判断主要是用在多终端登录的情况下)
                            if (![imamsg isMineMsg])
                            {
                                self.unReadMessageCount++;
                            }
                            [self updateOnChat:imaconv moveFromIndex:i];
                        }
                    }
                    //                }
                    updateSucc = YES;
                    break;
                }
            }
            
            if (!updateSucc && _refreshStyle == EIMARefresh_None)
            {
                            if (isSystemMsg)
                            {
//                                NSString *receiverid = [IMACustomConversation getCustomConversationID:imamsg];
                //                TIMConversation *imconv = [[TIMManager sharedInstance] getConversation:TIM_SYSTEM receiver:receiverid];
                //                [imconv setReadMessage];
                //                // 说明会话列表中没有该会话，新生建会话，并更新到
                //                IMACustomConversation *temp = [[IMACustomConversation alloc] initWith:imconv andMsg:imamsg];
                //                if (temp)
                //                {
                //                    __weak IMAConversationManager *ws = self;
                //                    [temp saveMessage:imamsg succ:^(int newUnRead) {
                //                        ws.unReadMessageCount += newUnRead;
                //                    }];
                //                    [_conversationList insertObject:temp atIndex:[self insertPosition]];
                //                    [self updateOnNewConversation:temp];
                //                }
//                                [msg remove];

                            }
                            else
                            {
                // 说明会话列表中没有该会话，新生建会话，并更新到
                IMAConversation *temp = [[IMAConversation alloc] initWith:conv];
                temp.lastMessage = imamsg;
                NSLog(@"fffmmmmm == %ld --- %ld",_conversationList.count,[self insertPosition] );
                                if ([[convcc getReceiver] isEqualToString:@"10001"]) {
                                    [[NSNotificationCenter defaultCenter] postNotificationName:@"pingkuntongzhi" object:imamsg];

                                }else {
                                    [_conversationList insertObject:temp atIndex:[self insertPosition]];
                                    [self updateOnNewConversation:temp];

                                }
                    if (![imamsg isMineMsg])
                    {
                        self.unReadMessageCount++;

                    }
                    }
            }

        }
    }
    }
}

-(UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

-(UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self getCurrentVC];
    
    if ([superVC isKindOfClass:[UITabBarController class]]) {
        
        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;
        
        if ([tabSelectVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
}



- (CustomElemCmd *)isOnlineMsg:(TIMElem *) elem
{
    if ([elem isKindOfClass:[TIMCustomElem class]])
    {
        CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
        if (elemCmd)
        {
            return elemCmd;
        }
    }
    return nil;
}
//申请加群请求
- (void)onAddGroupRequest:(TIMGroupSystemElem *)item
{

}

- (void)onAddFreindRequest:(TIMSNSSystemElem *)elem
{
}

@end


@implementation IMAConversationManager (Protected)

- (void)onConnect
{
    // 删除
    IMAConnectConversation *conv = [[IMAConnectConversation alloc] init];
    NSInteger index = [_conversationList indexOfObject:conv];
    if (index >= 0 && index < [_conversationList count])
    {
        [_conversationList removeObject:conv];
        [self updateOnDelete:conv atIndex:index];
    }
}
- (void)onDisConnect
{
    
    // 插入一个网络断开的fake conversation
    IMAConnectConversation *conv = [[IMAConnectConversation alloc] init];
    NSInteger index = [_conversationList indexOfObject:conv];
    if (!(index >= 0 && index < [_conversationList count]))
    {
        [_conversationList insertObject:conv atIndex:0];
        [self updateOnNewConversation:conv];
    }
}

- (void)updateOnChat:(IMAConversation *)conv moveFromIndex:(NSUInteger)index
{
    NSInteger toindex = [self insertPosition];
    
    if (index != toindex)
    {
        [_conversationList removeObjectAtIndex:index];
        
        [_conversationList insertObject:conv atIndex:toindex];
        
        
        // 更新界面
        IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_BecomeActiveTop];
        item.conversation = conv;
        item.index = index;
        item.toIndex = toindex;
        
        if (_conversationChangedCompletion)
        {
            _conversationChangedCompletion(item);
        }
        
        [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];
    }
    
    
}

- (void)updateOnDelete:(IMAConversation *)conv atIndex:(NSUInteger)index
{
    // 更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_DeleteConversation];
    item.conversation = conv;
    item.index = index;
    if (_conversationChangedCompletion)
    {
        _conversationChangedCompletion(item);
    }
    
    [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];
}

- (void)updateOnAsyncLoadContactComplete
{
    // 通知更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_SyncLocalConversation];
    if (_conversationChangedCompletion)
    {
        _conversationChangedCompletion(item);
    }
    [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];
}

- (void)updateOnLocalMsgComplete
{
    // 更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_SyncLocalConversation];
    if (_conversationChangedCompletion)
    {
        _conversationChangedCompletion(item);
    }
    [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];
}


- (void)updateOnLastMessageChanged:(IMAConversation *)conv
{
    if ([_chattingConversation isEqual:conv])
    {
        NSInteger index = [_conversationList indexOfObject:conv];
        NSInteger toindex = 0;
        if (index > 0 && index < [_conversationList count])
        {
            [_conversationList removeObject:conv];
            [_conversationList insertObject:conv atIndex:toindex];
            [self updateOnChat:conv moveFromIndex:index toIndex:toindex];
        }
        else if (index < 0 || index > [_conversationList count])
        {
            [_conversationList insertObject:conv atIndex:[self insertPosition]];
            [self updateOnNewConversation:conv];
        }
        else
        {
            // index == 0 不作处理
        }
    }
}

- (void)updateOnChat:(IMAConversation *)conv moveFromIndex:(NSUInteger)index toIndex:(NSInteger)toIdx
{
    // 更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_BecomeActiveTop];
    item.conversation = conv;
    item.index = index;
    item.toIndex = toIdx;
    
    if (_conversationChangedCompletion)
    {
        _conversationChangedCompletion(item);
    }
    
    [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];
}

- (void)updateOnNewConversation:(IMAConversation *)conv
{
    // 更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_NewConversation];
    item.conversation = conv;
    item.index = [_conversationList indexOfObject:conv];
    
    if (_conversationChangedCompletion)
    {
        _conversationChangedCompletion(item);
    }
    
    [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];
}

- (void)updateOnConversationChanged:(IMAConversation *)conv
{
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_ConversationChanged];
    item.conversation = conv;
    item.index = [_conversationList indexOfObject:conv];
    
    if (_conversationChangedCompletion)
    {
        _conversationChangedCompletion(item);
    }
    [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];
}
- (void)onAddToBlackList:(IMAConversation *)user
{
    if ([_conversationList containsObject:user]) {
        [_conversationList removeObject:user];
        [[TIMManager sharedInstance] deleteConversation:[user type] receiver:[user receiver]];
        IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_SyncLocalConversation];
        if (_conversationChangedCompletion)
        {
            _conversationChangedCompletion(item);
        }
        [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];


    }
}
- (void)onMoveFromBlackList:(IMAConversation *)user {
    if ([_conversationList containsObject:user]) {
        
    }else {
        [_conversationList insertObject:user atIndex:0];
        IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_SyncLocalConversation];
        if (_conversationChangedCompletion)
        {
            _conversationChangedCompletion(item);
        }
        [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];

    }

}



@end
